﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Interfaces.CommonData;
using StockInfoLoader;
using StockInfoDataLayer;

namespace StockInfoFacade.Adapters
{
    internal class StockInfoLoaderThreadAdapter
    {
        readonly object _bwLocker = new object();
        internal class BW_Metrics
        {
            

            private int _currentlyLoadedStocks;
            private int _allStocksToLoad;
            private BackgroundWorker _bw;


            public BW_Metrics(int currentlyLoadedStocks, int allStocksToLoad, BackgroundWorker bw)
            {
                _currentlyLoadedStocks = currentlyLoadedStocks;
                _allStocksToLoad = allStocksToLoad;
                _bw = bw;
            }


            public int currentlyLoadedStocks
            {
                get { return _currentlyLoadedStocks; }
                set
                {
                    _currentlyLoadedStocks = value;
                }

            }

            public int allStocksToLoad
            {
                get { return _allStocksToLoad; }
            }

            public BackgroundWorker Bw
            {
                get { return _bw; }
            }
        }

        private string _ticker;
        private int _stockId;
        private DateInterval _fromTo;
        private BW_Metrics _bwm;
        private PriceTable _pt;

        public  StockInfoLoaderThreadAdapter(string ticker, int stockId, DateInterval fromTo, PriceTable pt, BW_Metrics bwm)
        {
            _ticker = ticker;
            _stockId = stockId;
            _fromTo = fromTo;
            _pt = pt;
            _bwm = bwm;
        }


        public void DoLoad()
        {
            SingleStockPriceLoader ldr = new SingleStockPriceLoader();
            // load prices from web
            var lstStockPrice = ldr.LoadAdjustedStockPrices(_ticker, _stockId, _fromTo);
            if (lstStockPrice != null)
            {
                // put them in database
                _pt.PopulateBulk(lstStockPrice);
            }
            if (_bwm.Bw == null) return;

            lock (_bwLocker)
            {
                _bwm.currentlyLoadedStocks++;
                _bwm.Bw.ReportProgress(100 * (_bwm.currentlyLoadedStocks * 100) / (_bwm.allStocksToLoad * 100));
            }
        }
    }

    
}
